import { ReactElement, useRef, useState, useEffect, useContext } from 'react'
import { Modal, Form, TreeSelect, FormInstance } from 'antd'
import { DataNode } from 'rc-tree-select/lib/interface'
import { awaitWrap } from '@src/assets/js/tool'
import { getTreeRequest } from './ajax'
import { Context } from '../../../../context'

const { Item } = Form

async function initTree (setTreeData: (v: DataNode[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getTreeRequest())
  if (e === null && d !== null) {
    setTreeData(d)
  }
}

interface Props {
  visible: boolean
  hide: () => void
}

function Main ({ visible, hide }: Props): ReactElement {
  const { updateCaseDetail, caseDetail } = useContext(Context)
  const formRef = useRef<FormInstance>(null)
  const [treeData, setTreeData] = useState<DataNode[]>([])
  useEffect(() => {
    initTree(setTreeData).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (visible && caseDetail !== null && c !== null) {
      c.setFieldsValue({ cause_action: caseDetail.cause_action })
    } else if (!visible && c !== null) {
      c.resetFields()
    }
  }, [caseDetail, formRef, visible])
  return (
    <Modal title='修改案由' visible={visible} onOk={() => formRef.current?.submit()} onCancel={hide} maskClosable>
      <Form ref={formRef} labelCol={{ flex: '80px' }} onFinish={d => updateCaseDetail(d)}>
        <Item name='cause_action' label='案由' rules={[{ required: true, message: '案由不能为空' }]}>
          <TreeSelect treeData={treeData} placeholder='请选择' showSearch />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
